//
//  EmoticonTextView.swift
//  emoticonKB
//
//  Created by mac on 16/3/27.
//  Copyright © 2016年 mac. All rights reserved.
//

import UIKit

class EmoticonTextView: UITextView {

    func insertImageText(emo: Emoticons){
    
        if emo.isEmpty {
        
            print("空表情")
            return
        }
        if emo.isDelete {
        
            //系统方法 回删
            deleteBackward()
            return
        }
        if emo.code != nil {
        
            replaceRange(selectedTextRange!, withText: emo.codeStr ?? "")
            return
        }

        let imageText = EmoticonTextAttachment.emoticonImageToimageText(emo, font: font!)
    
        //3.获取当前文本输入框显示的属性文本
        let strM = NSMutableAttributedString(attributedString: attributedText)
        
        //替换文本之前 记录选中的位置
        let range = selectedRange
        
        //4.将图片的属性文本 替换到具体的位置
        strM.replaceCharactersInRange(selectedRange, withAttributedString: imageText)
        
        //5.重新设置textView的属性文本
        attributedText = strM
        //6.恢复光标的位置
        selectedRange = NSRange(location: range.location + 1, length: 0)
    }
    
    //获取完整的字符串
    func fullText() -> String {
        
        var strM = String()
        attributedText.enumerateAttributesInRange(NSRange(location: 0, length: attributedText.length), options: []) { (dict, range, _) -> Void in
            if let attachment = dict["NSAttachment"] as? EmoticonTextAttachment {
                //                print("是图片")
                //                print(attachment.chs)
                strM += (attachment.chs ?? "")
            } else {
                //                print("是文字")
                let str = (self.text as NSString).substringWithRange(range)
                strM += str
            }
            //            print(dict)
            //            print("---------------")
            //            print(range)
//            print(strM)
        }
        return strM
    }

}
